package zhxt.helmet.controller;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import zhxt.helmet.service.ResultService;

import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

@Controller
@RequestMapping(value = "result")
public class ResultController {
    @Autowired
    private ResultService resultService;

    @RequestMapping(value = "/analyse", produces = "text/html;charset=UTF-8")
    @ResponseBody
    public String analyse(@RequestParam("cameraList") String cameraList,
                          @RequestParam("startTime") String startTime,
                          @RequestParam("endTime") String endTime) throws JsonProcessingException {
        //将String类型的cameraList转为int列表
        // 去除字符串两端的中括号
        if (cameraList.length()==2)
            cameraList="";
        else
            cameraList = cameraList.substring(2, cameraList.length() - 2);
        // 按逗号分隔字符串得到字符串数组
        String[] strArray = cameraList.split("\",\"");
        // 使用 Java 8 的 Stream API 将字符串数组中的元素转换为整数并收集到列表中
        List<Integer> intList = Arrays.stream(strArray)
                .map(Integer::parseInt)
                .collect(Collectors.toList());
        Timestamp st =  Timestamp.valueOf(startTime);
        Timestamp ed = Timestamp.valueOf(endTime);
        List<List<Integer>> r = resultService.analyse(intList,st,ed);
        ObjectMapper objectMapper = new ObjectMapper();
        return objectMapper.writeValueAsString(r);
    }
}
